package com.fadadianqi.logistics.admin.controller;

import com.fadadianqi.logistics.admin.controller.form.AjaxResult;
import com.fadadianqi.commons.JSONProvider;
import com.fadadianqi.commons.ParamHelper;
import com.fadadianqi.goods.model.Goods;
import com.fadadianqi.goods.service.GoodsService;
import com.fadadianqi.logistics.inventory.model.Item;
import com.fadadianqi.logistics.inventory.model.Storehouse;
import com.fadadianqi.logistics.inventory.service.InventoryService;
import com.fadadianqi.logistics.inventory.service.StorehouseService;
import com.yeqiangwei.commons.util.BeanUtils;
import com.yeqiangwei.commons.util.ParamUtils;
import com.yeqiangwei.commons.util.ValidatorHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * 库房管理
 *
 * @author aroot
 */
@Controller
public class StorehouseController {

    @RequestMapping(value = "/a/store/dispatch/save", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> ajaxDispatchSave(HttpServletRequest request) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "text/html; charset=utf-8");
        String goodsId = ParamUtils.getString(request, "goodsId", null);
        String fromId = ParamUtils.getString(request, "fromId", null);
        if ("0".equals(fromId)) {
            fromId = null;
        }
        String storehouseId = ParamUtils.getString(request, "storehouseId", null);
        if ("0".equals(storehouseId)) {
            storehouseId = null;
        }
        int num = ParamUtils.getInt(request, "num", 0);
        inventoryService.dispatchStorehouse(goodsId, fromId, storehouseId, num);
        AjaxResult rs = new AjaxResult(null, Boolean.TRUE, null);
        return new ResponseEntity<String>(JSONProvider.toJSON(rs),
                responseHeaders, HttpStatus.OK);
    }

    /**
     * 统计某库房内存储未销售的货物数量
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/a/store/dispatch/count", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<String> ajaxDispatchCount(HttpServletRequest request) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "text/html; charset=utf-8");
        String goodsId = ParamUtils.getString(request, "gid", null);
        String storehouseId = ParamUtils.getString(request, "shid", "0");
        if ("0".equals(storehouseId)) {
            storehouseId = null;
        }
        AjaxResult rs = null;
        int total = inventoryService.countByGoodsIdAndStorehouseIdAndStatus(
                goodsId, storehouseId, Item.STATUS_NORMAL);
        rs = new AjaxResult(total, Boolean.TRUE, null);
        return new ResponseEntity<String>(JSONProvider.toJSON(rs),
                responseHeaders, HttpStatus.OK);
    }

    /**
     * 根据商品ID获取商品所在库房的库房列表
     *
     * @param request
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/a/store/dispatch/storehouse/list", method = RequestMethod.GET)
    public String ajaxStorehouseFrom(HttpServletRequest request, ModelMap modelMap) {
        List<Storehouse> list = storehouseService.findAll();
        modelMap.put("storehouseList", list);
        return "admin/store/dispatch/storehouseList";
    }

    @RequestMapping(value = "/a/store/dispatch", method = RequestMethod.GET)
    public String ajaxShowForm(HttpServletRequest request, ModelMap modelMap) {
        String goodsId = ParamUtils.getString(request, "gid", null);
        Goods goods = goodsService.getGoodsById(goodsId);
        List<Storehouse> list = storehouseService.findAll();
        if (goods != null) {
            modelMap.put("goods", goods);
            modelMap.put("brand", goodsService.getBrandById(goods.getBrandId()));
            modelMap.put("category", goodsService.getCategoryById(goods.getCategoryId()));
            /*List<Storehouse> fromList = new ArrayList<Storehouse>();
			if(ValidatorHelper.isNotEmpty(list)) {
				for(Storehouse item : list) {
					fromList.add(item);
				}
			}
			modelMap.put("fromList", fromList);*/
        }
        modelMap.put("storehouseList", list);
        return "admin/store/dispatch";
    }


    @RequestMapping(value = "/a/store/house")
    public String showIndex(ModelMap modelMap) {
        List<Storehouse> list = storehouseService.findAll();
        modelMap.put("houses", list);
        return "admin/store/house";
    }

    @RequestMapping(value = "/a/ajax/store/house/form/{id}", method = RequestMethod.GET)
    public String ajaxShowForm(@PathVariable String id, ModelMap modelMap) {
        Storehouse storehouse = storehouseService.getStorehouseById(id);
        modelMap.put("storehouse", storehouse);
        return "admin/store/houseForm";
    }

    @RequestMapping(value = "/a/ajax/store/house/save", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> ajaxSave(@ModelAttribute Storehouse form) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "text/html; charset=utf-8");
        AjaxResult rs = null;
        try {
            Storehouse po = storehouseService.getStorehouseById(form.getId());
            if (po == null) {
                po = new Storehouse();
                BeanUtils.copyProperties(form, po);
            } else {
                po.setName(form.getName());
            }
            storehouseService.save(po);
            rs = new AjaxResult(po, Boolean.TRUE, null);
        } catch (Exception e) {
            String msg = messageSource.getMessage(e.getMessage(), null, Locale.getDefault());
            rs = new AjaxResult(null, Boolean.FALSE, msg);
        }
        return new ResponseEntity<String>(JSONProvider.toJSON(rs),
                responseHeaders, HttpStatus.OK);
    }

    @RequestMapping(value = "/a/ajax/store/house/del/{id}", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> ajaxDel(@PathVariable String id) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "text/html; charset=utf-8");
        AjaxResult rs = null;
        try {
            Storehouse storehouse = storehouseService.getStorehouseById(id);
            storehouseService.del(storehouse);
            rs = new AjaxResult(storehouse, Boolean.TRUE, null);
        } catch (Exception e) {
            String msg = messageSource.getMessage(e.getMessage(), null, Locale.getDefault());
            rs = new AjaxResult(null, Boolean.FALSE, msg);
        }
        return new ResponseEntity<String>(JSONProvider.toJSON(rs),
                responseHeaders, HttpStatus.OK);
    }

    @RequestMapping("/a/ajax/store/house/count")
    public String chooseStorehouse(HttpServletRequest request, ModelMap modelMap) {
        String gid = ParamHelper.getGoodsId(request, null);
        Goods goods = goodsService.getGoodsById(gid);
        List<Storehouse> list = storehouseService.findAll();
        List<StorehouseVO> storehouseList = new ArrayList<StorehouseVO>();
        int noneTotal = storehouseService.countGoods(goods, null);
        int total = noneTotal;
        if (ValidatorHelper.isNotEmpty(list)) {
            for (Storehouse sh : list) {
                StorehouseVO vo = new StorehouseVO();
                BeanUtils.copyProperties(vo, sh);
                vo.setCount(storehouseService.countGoods(goods, sh));
                storehouseList.add(vo);
                total += vo.getCount();
            }
        }
        modelMap.put("noneTotal", noneTotal);
        modelMap.put("storehouseList", storehouseList);
        modelMap.put("total", total);
        modelMap.put("gid", gid);
        return "/admin/store/count";
    }

    @Autowired
    private MessageSource messageSource;

    @Autowired
    private StorehouseService storehouseService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private InventoryService inventoryService;

    public static class StorehouseVO extends Storehouse {

        /**
         *
         */
        private static final long serialVersionUID = -2523594187695826201L;

        private int count;

        public int getCount() {
            return count;
        }

        public void setCount(int count) {
            this.count = count;
        }
    }
}
